package com.digital.herbarium.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.digital.herbarium.Entity.SystemInfo;
import com.digital.herbarium.Exception.CustomException;
import com.digital.herbarium.Mapper.SystemInfoMapper;
import com.digital.herbarium.Util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SystemInfoService {

    @Autowired
    SystemInfoMapper systemInfoMapper;

    public List<SystemInfo> getSystemInfo(SystemInfo systemInfo){
        return systemInfoMapper.getSystemInfo(systemInfo);
    }


    public  void  addSystemInfo(SystemInfo systemInfo){
        checkPar(systemInfo);

        systemInfo.setState(1);
        systemInfo.setCreatetime(TimeUtil.getNow());

        systemInfoMapper.addSystemInfo(systemInfo);
    }


    public void editSystemInfo(SystemInfo systemInfo){
        checkPar(systemInfo);
        if(systemInfo.getId() == null || systemInfo.getId() == 0){
            addSystemInfo(systemInfo);
        }else{
            systemInfoMapper.editSystemInfo(systemInfo);
        }

    }

    public void checkPar(SystemInfo systemInfo){
        if(!StrUtil.hasEmpty(systemInfo.getLinktel()) && !StrUtil.hasBlank(systemInfo.getLinktel()) &&
                !Validator.isMobile(systemInfo.getLinktel())){
            throw new CustomException(400,"请输入正确的手机号");
        }

        if(!StrUtil.hasEmpty(systemInfo.getEmail()) && !StrUtil.hasBlank(systemInfo.getEmail()) &&
                !Validator.isEmail(systemInfo.getEmail())){
            throw new CustomException(400,"请输入正确的邮箱地址");
        }
    }


    public  void delSystemInfo(String id){
        if(StrUtil.hasEmpty(id) || StrUtil.hasBlank(id)){
            throw  new CustomException(400,"缺少信息id");
        }
        String[] strArr = id.split(",");
        Long[] ids = Convert.toLongArray(strArr);
        systemInfoMapper.delSystemInfo(ids);
    }
}
